package com.zyw.module.console.sys.service;

import com.zyw.module.console.sys.dao.MenuDao;
import com.zyw.module.console.sys.po.Menu;
import com.zyw.module.console.sys.vo.MenuTreeVo;
import com.zyw.mvc.support.BaseService;
import com.zyw.orm.support.page.Page;

import java.util.LinkedList;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class MenuService extends BaseService<Menu, Integer, MenuDao> {

    public Menu get(Integer id) {
        return getDao().selectByPrimaryKey(id);
    }

    @Transactional
    public int insert(Menu record) {
        return getDao().insert(record);
    }

    @Transactional
    public int update(Menu record) {
        return getDao().updateByPrimaryKey(record);
    }

    @Transactional
    public int delete(Integer id) {
        return getDao().deleteByPrimaryKey(id);
    }

    public List<Menu> findByPage(Page<Menu> page) {
        List<Menu> list = getDao().findByPage(page);
        page.setList(list);
        return list;
    }

    public List<MenuTreeVo> getMenuTreeList(Integer sysid) {
        List<Menu> list = getDao().findMenuTreeList(sysid);

        List<MenuTreeVo> vos = new LinkedList<>();
        if (list != null) {
            for (Menu menu : list) {
                vos.add(new MenuTreeVo(menu));
            }
        }

        return getMenuByPid(vos, 0);
    }

    private List<MenuTreeVo> getMenuByPid(List<MenuTreeVo> vos, int pid) {
        List<MenuTreeVo> answer = new LinkedList<MenuTreeVo>();
        for (MenuTreeVo vo : vos) {
            if (vo.getPid() == pid) {
                vo.setSubs(getMenuByPid(vos, vo.getId()));
                vo.setHasChilds(!vo.getSubs().isEmpty());
                answer.add(vo);
            }
        }
        return answer;
    }
}